/**
 *  需求：添加商品，添加购物车的数据操作
 *  1. 创建两个切片：  goodsSlice【商品】  carSlice【购物车】
 *  2. 添加商品
 *  3. 添加购物车
 * 
 */

// 1. 导入 createSlice  configureStore
import { createSlice, configureStore } from '@reduxjs/toolkit'

// 2. 创建商品切片
const goodsSlice = createSlice({
    name: 'goods',
    initialState: {
        goodsList: []
    },
    reducers: {
        addGoods(state, { payload }) {
            state.goodsList.push({
                id:Math.random().toString(36).slice(2),
                ...payload
            })
        }
    }
})


// 3. 创建购物车切片
const carSlice = createSlice({
    name:'car',
    initialState:{
        carList:[]
    },
    reducers:{
        addCar(state, {payload}){
            console.log('payload: ', payload)
            // 1. 判断id商品是否已在购物车，如果在将buyNum数据 + 1，不在新增
            let index = state.carList.findIndex(item=>item.id === payload.id)
            if(index !== -1){
                state.carList[index].buyNum += 1
            }else{
                state.carList.push({
                    ...payload,
                    buyNum:1
                })
            }
            
        }
    }
})
// 4. 获取actionCreator [产品经理]
const {addGoods} = goodsSlice.actions
const {addCar} = carSlice.actions

// 5. 创建store

const store = configureStore({
    reducer:{
        goods:goodsSlice.reducer,
        car:carSlice.reducer
    }
})
// 6. 监听数据变化
store.subscribe(()=>{
    console.log('state: ', store.getState())
})

// 7. 添加商品 store.dispatch(action)

store.dispatch(addGoods({gname:'小米手机', price:1999}))
store.dispatch(addGoods({gname:'mate50pro', price:7799}))

// 8. 添加购物车

store.dispatch(addCar(store.getState().goods.goodsList[0]))
store.dispatch(addCar(store.getState().goods.goodsList[1]))
store.dispatch(addCar(store.getState().goods.goodsList[1]))